<script setup lang="ts">
import { ref, defineProps, watch, onMounted, onBeforeUnmount, withDefaults } from 'vue'
import * as echarts from 'echarts'
import type { ECBasicOption, EChartsType } from 'echarts/types/dist/shared'
import { type EventParams} from "@/config";
import light_theme from './westeros.json'
import dark_theme from './chalk.json'
interface EchartsProps {
  options: ECBasicOption | null
  width?: string|number
  height?: string|number
  handlerClick?: (params: EventParams) => void | null
}
let instance: EChartsType = null as unknown as EChartsType
//withDefaults可以设置默认值 这里我们需要初始化就设置子组件的默认宽度高度
const props = withDefaults(defineProps<EchartsProps>(), {
  width: '100%',
  height: '100%'
})
function changeStr(param: string|number):string{
  if(typeof param==="string"){
    return  param
  }
  return param+'px'
}
//搭配写法一
// const main = ref(null)
//搭配写法二
const main = ref<HTMLElement | null>(null)
// 初始化图表
const initEcharts = () => {
  if (props.options == null) return
// 写法一 as unknown as HTMLElement 定义的是document.getElementById 类似于这种方式拿值 的 数据类型
  echarts.registerTheme('westeros', light_theme)
  instance = echarts.init(main.value as unknown as HTMLElement,'westeros') as unknown as EChartsType
  instance.setOption(props.options as ECBasicOption)
  instance.on('click', handlerClick)
  window.onresize = handlerSize
  // 写法二
  // let mainValue = main.value
  // if(mainValue){ // 判断是否为空
  // 	instance = echarts.init(mainValue) as unknown as EChartsType
  // 	instance.setOption(props.options as ECBasicOption)
  // 	instance.on('click', handlerClick)
  // 	window.onresize = handlerSize
  // }
}
function handlerSize() {
  instance.resize()
}
function handlerClick(params: EventParams | any): void {
  if (props.handlerClick != null) {
    props.handlerClick(params)
  }
}
onMounted(() => {
  initEcharts()
})
onBeforeUnmount(() => {
  if (instance) {
    instance.dispose()
    window.removeEventListener('onresize', handlerSize)
  }
})
watch(props, () => {
  if (instance) {
    instance.setOption(props.options as ECBasicOption)
  } else {
    initEcharts()
  }
})
</script>

<template>
  <div ref="main" class="main" :style="{ width: changeStr(width), height: changeStr(height) }" />
</template>

<style scoped lang="scss">
  .main {
    width: 100%;
    height: 100%;
  }
</style>